package com.ruoyi.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.appuser.domain.Appuser;
import com.ruoyi.appuser.domain.AppuserPrizeRecord;
import com.ruoyi.appuser.domain.vo.AppuserPlayVO;
import com.ruoyi.appuser.domain.vo.AppuserVO;
import com.ruoyi.appuser.domain.vo.PrizeInfo;
import com.ruoyi.appuser.service.IAppuserPrizeRecordService;
import com.ruoyi.appuser.service.IAppuserService;
import com.ruoyi.common.annotation.PassToken;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.integral.domain.Integral;
import com.ruoyi.integral.service.IIntegralService;
import com.ruoyi.locker.domain.Locker;
import com.ruoyi.locker.service.ILockerService;
import com.ruoyi.normal.domain.AppuserAchievementPrize;
import com.ruoyi.normal.service.IAppuserAchievementPrizeService;
import com.ruoyi.season.domain.PlaySeasonPrize;
import com.ruoyi.season.domain.PlaySeasonRecord;
import com.ruoyi.season.domain.vo.PlaySeasonInfoVo;
import com.ruoyi.season.domain.vo.PrizeInfoVo;
import com.ruoyi.season.service.IPlaySeasonPrizeService;
import com.ruoyi.season.service.IPlaySeasonRecordService;
import com.ruoyi.season.service.IPlaySeasonService;
import com.ruoyi.util.AuthUtil;
import com.ruoyi.util.WechatConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author mjl
 */
@RestController
@RequestMapping("/app-api/season")
@Api(value = "赛季",tags = "移动端接口")
public class AppSesonController {

    @Resource
    private IAppuserService appuserService;
    @Resource
    private ILockerService lockerService;
    @Resource
    private IPlaySeasonService playSeasonService;
    @Resource
    private IAppuserAchievementPrizeService appuserAchievementPrizeService;
    @Resource
    private IPlaySeasonPrizeService playSeasonPrizeService;
    @Resource
    private IPlaySeasonRecordService playSeasonRecordService;
    @Resource
    private IIntegralService integralService;
    @Resource
    private IAppuserPrizeRecordService appuserPrizeRecordService;


    //    @GetMapping("/info")
//    @ApiOperation(value = "赛季信息", notes = "")
    public R bindMobile( ) {
        String loginUserId = AuthUtil.getAppUserId();
        HashMap<String,Object> map = new HashMap(6);
        AppuserVO appuser = appuserService.getUserInfo(loginUserId);

        List<PrizeInfo> prizeResult = new ArrayList<>();
        List<PrizeInfo> currentPrizeResult = new ArrayList<>();

        if(appuser.getIsVip() == 1){
            /**普通用户*/
            appuser.setShowIntegral(appuser.getNormalIntegral());
            AppuserAchievementPrize achievementPrize = appuserAchievementPrizeService.getOne(
                    new LambdaQueryWrapper<AppuserAchievementPrize>());
            /**奖品信息*/
            if(Objects.nonNull(achievementPrize)){
                PrizeInfo prizeInfo = new PrizeInfo();
                prizeInfo.setIntegral(achievementPrize.getIntegral());
                prizeInfo.setPicture(achievementPrize.getPicture());
                prizeInfo.setPrizeName(achievementPrize.getPrizeName());
                prizeInfo.setId(achievementPrize.getId());
                prizeInfo.setIsAchieved(1);
                prizeResult.add(prizeInfo);

                PrizeInfo prizeInfo1 = new PrizeInfo();
                prizeInfo1.setIntegral(achievementPrize.getIntegral());
                prizeInfo1.setPicture(achievementPrize.getPicture());
                prizeInfo1.setPrizeName(achievementPrize.getPrizeName());
                prizeInfo1.setId(achievementPrize.getId());
                currentPrizeResult.add(prizeInfo1);
            }

        }else if(appuser.getIsVip() == 2){
            /**会员用户*/
            appuser.setShowIntegral(appuser.getVipIntegral());

            PlaySeasonRecord playRecord = playSeasonRecordService.getById(appuser.getPlaySeasonRecordId());
            /**获得未领取奖品信息*/
            List<PlaySeasonPrize> noPrizeInfo = playSeasonPrizeService
                    .selectPlayCurrentPrize(playRecord.getId(),playRecord.getPlaySeasonId());

            /**奖品信息*/
            if(noPrizeInfo.size() > 0){
                PlaySeasonPrize vipPrize = noPrizeInfo.get(0);
                PrizeInfo vipPrizeInfo = new PrizeInfo();
                vipPrizeInfo.setPicture(vipPrize.getPicture());
                vipPrizeInfo.setIntegral(vipPrize.getIntegral());
                vipPrizeInfo.setPrizeName(vipPrize.getPrizeName());
                vipPrizeInfo.setId(vipPrize.getId());
                currentPrizeResult.add(vipPrizeInfo);
            }
            prizeResult = playSeasonPrizeService.selectPrizeInfo(loginUserId,playRecord.getPlaySeasonId(),
                    appuser.getPlaySeasonRecordId());

        }

        map.put("showIntegral",appuser.getShowIntegral());
        map.put("currentPrize",currentPrizeResult);
        map.put("prizeInfo",prizeResult);
       return R.ok(map);
    }

    @GetMapping("/list")
    @ApiOperation(value = "赛季列表", notes = "type 1我的赛季2vip赛季")
    public R seasonList(@RequestParam(defaultValue = "1") Integer type,@RequestParam(name = "pageNo" ,defaultValue = "1") Integer pageNo
            ,@RequestParam(name = "pageSize",defaultValue = "10") Integer pageSize) {
        String loginUserId = AuthUtil.getAppUserId();
        IPage<PlaySeasonInfoVo> page = new Page<PlaySeasonInfoVo>(pageNo,pageSize);

        List<PlaySeasonInfoVo> playList = new ArrayList<>();

        if(type == 1){
            playList = playSeasonRecordService.selectAppuserSeasonByUserId(page,loginUserId);

        }else if(type == 2){
            playList = playSeasonService.selectPlaySeasonInfo(page);

        }

        return R.ok(page.setRecords(playList));
    }

    @PostMapping("/selectSeason")
    @ApiOperation(value = "切换赛季", notes = "playSeasonRecordId当前赛季id")
    public R selectSeason(String playSeasonRecordId) {
        if(StringUtils.isBlank(playSeasonRecordId)){
           return R.fail("参数错误");
        }
        String loginUserId = AuthUtil.getAppUserId();
        PlaySeasonRecord playInfo = playSeasonRecordService.getById(playSeasonRecordId);
        if(Objects.isNull(playInfo)){
           return R.fail("赛季信息异常");
        }
        if(!playSeasonRecordService.update(new LambdaUpdateWrapper<PlaySeasonRecord>()
                .set(PlaySeasonRecord::getStatus,1)
                .eq(PlaySeasonRecord::getAppuserId,loginUserId)
                .ne(PlaySeasonRecord::getStatus,3)
        )){
            return R.fail("赛季更新失败");
        }

        if(!playSeasonRecordService.update(new LambdaUpdateWrapper<PlaySeasonRecord>()
                .set(PlaySeasonRecord::getStatus,2)
                .eq(PlaySeasonRecord::getAppuserId,loginUserId)
                .eq(PlaySeasonRecord::getId,playSeasonRecordId)
        )){
            return R.fail("赛季更新失败");
        }

        if(!appuserService.update(new LambdaUpdateWrapper<Appuser>()
                .set(Appuser::getIsVip,playInfo.getType())
                .set(Appuser::getVipTime,playInfo.getBeginTime())
                .set(Appuser::getUpdateTime,new Date())
                .set(Appuser::getPlaySeasonRecordId,playSeasonRecordId)
                .eq(Appuser::getId,loginUserId)
        )){
            return R.fail("更新用户信息失败");
        }

        return R.ok();
    }


    @PostMapping("/isGet")
    @ApiOperation(value = "领取奖品", notes = " ")
    public R seasonList(String prizeId) {
        if(StringUtils.isBlank(prizeId)){
           return R.fail("奖品异常");
        }
        String loginUserId = AuthUtil.getAppUserId();
        AppuserVO appuser = appuserService.getUserInfo(loginUserId);
        Date date = new Date();

        PlaySeasonPrize prizeInfo = playSeasonPrizeService.getById(prizeId);

        if(Objects.isNull(prizeInfo) || StringUtils.isBlank(prizeInfo.getId())){
            return R.fail("奖品异常");
        }
        BigDecimal afterIntegral = new BigDecimal(0);
        if(appuser.getIsVip() == 1){
            appuser.setShowIntegral(appuser.getNormalIntegral());
            /**积分与奖励积分校验*/
            if(appuser.getNormalIntegral().compareTo(prizeInfo.getIntegral()) == -1){
                return R.fail("积分不足");
            }
            afterIntegral = appuser.getShowIntegral().subtract(prizeInfo.getIntegral());

            if(!appuserService.update(new LambdaUpdateWrapper<Appuser>()
                    .set(Appuser::getNormalIntegral,afterIntegral)
                    .set(Appuser::getUpdateTime,date)
                    .eq(Appuser::getId,loginUserId)
            )){
                return R.fail("更新用户积分失败");
            }
        }else if(appuser.getIsVip() == 2){
            appuser.setShowIntegral(appuser.getVipIntegral());
            /**积分与奖励积分校验*/
            if(appuser.getVipIntegral().compareTo(prizeInfo.getIntegral()) == -1){
                return R.fail("积分不足");
            }
            afterIntegral = appuser.getShowIntegral().subtract(prizeInfo.getIntegral());

            if(!appuserService.update(new LambdaUpdateWrapper<Appuser>()
                    .set(Appuser::getVipIntegral,afterIntegral)
                    .set(Appuser::getUpdateTime,date)
                    .eq(Appuser::getId,loginUserId)
            )){
                return R.fail("更新用户积分失败");
            }
        }

        Integral insertIntegral = new Integral();
        insertIntegral.setContent(prizeInfo.getPrizeName());
        insertIntegral.setAppuserId(loginUserId);
        insertIntegral.setBalance(afterIntegral);
        insertIntegral.setProfit(prizeInfo.getIntegral());
        insertIntegral.setType(1);
        insertIntegral.setCreateTime(date);
        if(!integralService.save(insertIntegral)){
            return R.fail("积分记录失败");
        }

        AppuserPrizeRecord prizeRecord = new AppuserPrizeRecord();
        prizeRecord.setAppuserId(loginUserId);
        prizeRecord.setCreateTime(date);
        prizeRecord.setPrizeName(prizeInfo.getPrizeName());
        prizeRecord.setPicture(prizeInfo.getPicture());
        prizeRecord.setPlaySeasonPrizeId(prizeId);
        prizeRecord.setPlaySeasonRecordId(appuser.getPlaySeasonRecordId());
        if(appuser.getIsVip() == 1){
            prizeRecord.setType(1);
        }else if(appuser.getIsVip() == 2){
            prizeRecord.setType(2);
        }
        if(!appuserPrizeRecordService.save(prizeRecord)){
            return R.fail("更新领奖记录失败");
        }

        Locker locker = new Locker();
        locker.setName(prizeInfo.getPrizeName());
        locker.setPicture(prizeInfo.getPicture());
        locker.setType(2);
        locker.setAppuserId(loginUserId);
        locker.setCreateTime(date);
        if(!lockerService.save(locker)){
            return R.fail("领取奖励失败");

        }

        return R.ok();
    }

    @GetMapping("/prizeInfo")
    @ApiOperation(value = "赛季奖品详情信息", notes = "playSeasonId赛季id及分页")
    public R prizeInfo(String playSeasonId,@RequestParam(name = "pageNo" ,defaultValue = "1") Integer pageNo
            ,@RequestParam(name = "pageSize",defaultValue = "10") Integer pageSize) {
        if(StringUtils.isBlank(playSeasonId)){
           return R.fail("赛季信息错误");
        }
        HashMap<String,Object> map = new HashMap(4);
        String loginUserId = AuthUtil.getAppUserId();
        AppuserVO appuser = appuserService.getUserInfo(loginUserId);
        IPage<PrizeInfoVo> page = new Page<PrizeInfoVo>(pageNo,pageSize);

        List<PrizeInfoVo> prizeInfoList = new ArrayList<>();

        /**当前用户展示积分*/
        if(appuser.getIsVip() == 1){
            appuser.setShowIntegral(appuser.getNormalIntegral());
            prizeInfoList =  playSeasonPrizeService.selectNormalUserPrizeInfo(page,playSeasonId);
            if(prizeInfoList.size() > 0){
                prizeInfoList.get(0).setIsGet(1);
                if(appuser.getShowIntegral().compareTo(prizeInfoList.get(0).getIntegral()) >= 0){
                    prizeInfoList.get(0).setIsGet(2);
                }
            }

        }else if(appuser.getIsVip() == 2){
            appuser.setShowIntegral(appuser.getVipIntegral());
            prizeInfoList =  playSeasonPrizeService.selectPrizeInfoById(page,
                    appuser.getPlaySeasonRecordId(),
                    playSeasonId);
            int count = 0;
            if(prizeInfoList.size() > 0){
                /**默认第一个奖品显示是否领取*/
                for(PrizeInfoVo temp : prizeInfoList)
                {
                    if(temp.getIsGet() == 1){

                        if(count == 1){
                            break;
                        }
                        if(appuser.getShowIntegral().compareTo(temp.getIntegral()) >= 0){
                            temp.setIsGet(2);
                        }
                        count++;
                    }

                }

            }
        }

        map.put("prizeInfoList",page.setRecords(prizeInfoList));
        map.put("showIntegral",appuser.getShowIntegral());
        return R.ok(map);
    }


}
